﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

public static class LevelData
{
    private static string DataJson = /*lang=json*/ @"{
        'Day1': {
            'DayString': {
                'Lines' : [
                    {
                        'Upper': ['你','好'],
                        'Lower': ['hello','world'],
                    },
                    {
                        'Upper': ['再','见'],
                        'Lower': ['good','bye'],
                    },
                ]
            }
        }
    }";

    public static bool GetStrData(int day, int line, int index, bool up, ref string output)
    {
        JObject Data = JObject.Parse(DataJson);
        JToken token = null;
        GetJsonInRecursion(Data, new List<System.Object> { "Day" + day, "DayString", "Lines", line, up ? "Upper" : "Lower" , index }, ref token);
        if (token is JValue)
        {
            output = token.ToString();
            return true;
        }
        else return false;

        //string output = Data["Day" + day]["DayString"]["Lines"][line][up == 1 ? "Upper" : "Lower"][index].ToString();
        //if (output != null) return output;
        //else return "";
    }

    //通用的递归读取json数据的函数
    //回传参数为是否存在数据，ref数据为实际数据
    private static bool GetJsonInRecursion(JToken jsonData, List<System.Object> param, ref JToken output)
    {
        if(param.Count == 1)
        {
            output = GetJData(jsonData, param[0]);
            return output != null;
        }
        else if (param.Count < 1) return false;
        else
        {
            JToken temp = GetJData(jsonData, param[0]);
            if (temp != null)
            {
                param.RemoveAt(0);
                return GetJsonInRecursion(temp, param, ref output);
            }
            else return false;
        }
    }
    
    //通用的不限制参数类型的获取json数据的函数
    //如果参数类型不匹配会回传null
    private static JToken GetJData(JToken data, System.Object param)
    {
        //Debug.Log(param);
        if (data is JObject)
        {
            JObject temp = data as JObject;
            return temp.GetValue(param.ToString());
        }
        else if (data is JArray)
        {
            JArray temp = data as JArray;
            int number;
            if (!int.TryParse(param.ToString(), out number) || temp.Count <= (int)param) return null;
            else return temp[number];
        }
        return null;
    }

}
